/**
 * 实现功能如下：
 * 1. 按帧读取视频ts文件
 * 视频帧是rgba格式，音频为pcm_s16
 *
 * 主要是通过filter完成下面的两个操作：
 * 1. video filter: 将yuv转为rgba
 * 2. audio filter: 将pcm float32转为pcm s16（暂未实现）
 *
 * 注意事项：
 * 1. 读取出来的数据最后都会有一些无效数据，需要手工清除掉
 */
const beamcoder = require('beamcoder');
const { writeData} = require("../../util/util");

let videoParam = {
    width: 448,
    height: 960,
}

//视频过滤器，用于将yuv转为RGBA
async function initVideoFilter(){
    return await beamcoder.filterer({
        filterType: 'video',
        //输入参数
        inputParams: [
            {
                width: videoParam.width,
                height: videoParam.height,
                pixelFormat: 'yuv420p',
                sample_aspect_ratio: 0,
                timeBase: [1,25],
                pixelAspect:[videoParam.width,videoParam.height]
            }
        ],
        //输出参数，需要输出为rgba
        outputParams: [
            {
                pixelFormat: 'rgba'
            }
        ],
        filterSpec: 'scale=448:960'
    });
}

async function read() {
    let demuxer = await beamcoder.demuxer('../media/test.ts');
    let videoDecoder = beamcoder.decoder({name: 'h264'});
    let audioDecoder = beamcoder.decoder({name: 'aac'});

    let videoFilter = await initVideoFilter();

    let audioCount = 0, videoCount = 0;
    let packet = {};
    for (let x = 0; x < 100 && packet != null; x++) {
        packet = await demuxer.read(); // Read next frame. Note: returns null for EOF
        if (packet) {
            if (packet.stream_index === 0) {
                let frames = await videoDecoder.decode(packet);
                //刚开始的几帧里面是空白数据，需要跳过
                if (frames.frames.length === 0) {
                    continue;
                }

                console.log(x, `${Date.now()},收到视频帧，frameLength:${frames.frames.length}, total_time:${frames.total_time}`);
                //默认读取出来的视频帧是yuv格式，需要调用filter将其转为rgba
                let filteredData = await videoFilter.filter([frames]);
                let realData = filteredData[0]?.frames[0]?.data;
                if (realData) {
                    //去掉最后面的对齐数据
                    realData = realData.slice(0, videoParam.width * videoParam.height * 4);
                    //将数据写入到文件中，便于查看是否正确
                    // await writeData(realData, `test${x}.rgba`);
                }
                videoCount++;
            } else if (packet.stream_index === 1) {
                let audioFrames = await audioDecoder.decode(packet);
                console.log(x, `>>>>${Date.now()},收到音频帧，frameLength:${audioFrames.frames.length}, total_time:${audioFrames.total_time}`);
                audioCount++;
            }
        }
    }
    console.log(`===================================`);
    console.log(`videoCount:${videoCount}, audioCount:${audioCount}`);

    let frames = await videoDecoder.flush(); // Must tell the videoDecoder when we are done
    console.log('flush', frames.total_time, frames.length);
}

read();